const { test, beforeEach, afterEach } = require('tap');
const core = require('../../..');
const vuserLauncher = core.runner.runner;
const { SSMS } = require('../../../lib/ssms');
const createTestServer = require('../../targets/simple_ws');

let server;
let port;
beforeEach(async () => {
  const serverInfo = await createTestServer();
  port = serverInfo.port;
  server = serverInfo.server;
});

afterEach(() => {
  server.close();
});

test('Subprotocols - using a known subprotocol', (t) => {
  const script = require('./scripts/subprotocols.json');
  script.config.target = `ws://127.0.0.1:${port}`;
  vuserLauncher(script).then((ee) => {
    ee.on('done', (nr) => {
      const report = SSMS.legacyReport(nr).report();
      console.log(report);
      t.equal(
        Object.keys(report.errors).length,
        0,
        'Test with a subprotocol should complete with no errors'
      );
      ee.stop().then(() => {
        t.end();
      });
    });

    ee.run();
  });
});

test('Subprotocols - no subprotocol', (t) => {
  const script = require('./scripts/subprotocols.json');
  script.config.target = `ws://127.0.0.1:${port}`;
  delete script.config.ws;

  vuserLauncher(script).then((ee) => {
    ee.on('done', (nr) => {
      const report = SSMS.legacyReport(nr).report();
      t.equal(
        Object.keys(report.errors).length,
        0,
        'Test with no subprotocol set should complete with no errors'
      );
      ee.stop().then(() => {
        t.end();
      });
    });

    ee.run();
  });
});

test('Subprotocols - unknown subprotocol', (t) => {
  const script = require('./scripts/subprotocols.json');
  script.config.target = `ws://127.0.0.1:${port}`;

  script.config.ws = {
    subprotocols: ['unsupportedByTheServer']
  };

  vuserLauncher(script).then((ee) => {
    ee.on('done', (nr) => {
      const report = SSMS.legacyReport(nr).report();
      t.equal(Object.keys(report.errors).length, 1, 'Should have one error');

      // FIXME: This test is coupled to the error message generated by the ws library
      t.ok(
        Object.keys(report.errors)[0].toLowerCase().indexOf('no subprotocol') >
          -1,
        'The error should be of "no subprotocol" type'
      );

      ee.stop().then(() => {
        t.end();
      });
    });

    ee.run();
  });
});
